﻿Imports System.IO
Imports NewHeaderSystems.Archive.Data

Public Class SetupDatabase
    Private Const OPTION_CREATE As Integer = 0
    Private Const OPTION_USE As Integer = 1

    Private Const TYPE_SQL_SERVER As Integer = 0
    Private Const TYPE_FILE As Integer = 1

    Private _configurationHelper As New ConfigurationHelper
    Private _isCreateDatabase As Boolean


    Public Property IsCreateDatabase() As Boolean
        Get
            Return cboCreateOrUse.SelectedIndex = OPTION_CREATE
        End Get
        Set(ByVal value As Boolean)
            If value Then
                cboCreateOrUse.SelectedIndex = OPTION_CREATE
            Else
                cboCreateOrUse.SelectedIndex = OPTION_USE
            End If
        End Set
    End Property

    Public Sub New(ByVal isCreateDatabase As Boolean)
        InitializeComponent()
        _isCreateDatabase = isCreateDatabase
    End Sub

    Private Sub SetupDatabase_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        _configurationHelper.GetDatabaseSettings(txtDatabasePath.Text, txtServer.Text, txtDatabase.Text)
        If (String.IsNullOrEmpty(txtDatabasePath.Text)) Then
            cboServerOrFile.SelectedIndex = TYPE_SQL_SERVER
        Else
            cboServerOrFile.SelectedIndex = TYPE_FILE
        End If
        IsCreateDatabase = _isCreateDatabase
    End Sub

    Private Sub btnTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If IsValidConnection() Then
            MessageBox.Show(Me, "Connected successfully!", "Connected", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        DialogResult = Windows.Forms.DialogResult.Cancel
        Me.Close()
    End Sub

    Private Sub btnOpenSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpenSave.Click
        Dim initialDirectory = String.Empty
        If Directory.Exists(txtDatabasePath.Text) Then
            initialDirectory = Path.GetDirectoryName(txtDatabasePath.Text)
            folderBrowserDialog.SelectedPath = initialDirectory
            openFileDialog.InitialDirectory = initialDirectory
        End If
        If IsCreateDatabase Then
            If folderBrowserDialog.ShowDialog() = DialogResult.OK Then
                txtDatabasePath.Text = Path.Combine(folderBrowserDialog.SelectedPath, "NHSArchive.mdf")
            End If
        Else
            If openFileDialog.ShowDialog() = DialogResult.OK Then
                txtDatabasePath.Text = openFileDialog.FileName
            End If
        End If
    End Sub

    Private Function IsValidConnection() As Boolean
        If ConnectionType = TYPE_FILE Then
            Return IsValidConnectionFile()
        Else
            Return IsValidConnectionServer()
        End If
    End Function

    Private Function IsValidConnectionFile() As Boolean
        Dim message As String = String.Empty
        Dim isValid As Boolean = False
        If Not File.Exists(txtDatabasePath.Text) Then
            MessageBox.Show(Me, "Please select a valid database file.", "File Does Not Exist", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Else
            isValid = _configurationHelper.TestConnectionFile(txtDatabasePath.Text, message)
            If Not isValid Then
                MessageBox.Show(Me, "Error: " + Environment.NewLine + message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If
        End If
        Return isValid
    End Function

    Private Function IsValidConnectionServer() As Boolean
        Dim message As String = String.Empty
        Dim isValid As Boolean = False
        Me.Cursor = Cursors.WaitCursor
        isValid = _configurationHelper.TestConnectionServer(txtServer.Text, txtDatabase.Text, message)
        Me.Cursor = Cursors.Default
        If Not isValid Then
            MessageBox.Show(Me, "Unable to connect to the specified server/database." + Environment.NewLine + "Please verify the server & database settings you provided. See below for more details." + Environment.NewLine + Environment.NewLine + "Error: " + Environment.NewLine + message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End If
        Return isValid
    End Function

    Private Function OpenDatabase() As Boolean
        Dim opened As Boolean = False
        If IsValidConnection() Then
            Try
                DataScript.CheckAndUpgradeDatabase()
                SaveConnectionString()
                opened = True
            Catch ex As Exception
                MessageBox.Show(Me, "Error: " + Environment.NewLine + ex.Message, "Error Upgrading Database", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End If
        Return opened
    End Function

    Private Function CreateDatabase() As Boolean
        Try
            If ConnectionType = TYPE_FILE Then
                Return CreateDatabaseFile()
            Else
                Return CreateDatabaseServer()
            End If
        Catch ex As Exception
            MessageBox.Show(Me, "Error: " + Environment.NewLine + ex.Message, "Error Creating Database", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return False
        End Try
    End Function

    Private Function CreateDatabaseFile() As Boolean
        Dim created As Boolean = False
        If String.Compare(Path.GetExtension(txtDatabasePath.Text), "mdf", True) = 0 Then
            txtDatabasePath.Text += ".mdf"
        End If
        Dim filePath As String = txtDatabasePath.Text

        If File.Exists(filePath) Then
            MessageBox.Show(Me, "Unable to overwrite. A database already exists at the path you selected.", "Error Creating Database", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Else
            DataScript.CreateDatabase(filePath)
            _configurationHelper.SaveConnectionStringFile(filePath) 'Connect to this new database

            MessageBox.Show(Me, "A new database has been created successfully. Please configure the system settings for this database.", "Database Created", MessageBoxButtons.OK, MessageBoxIcon.Information)
            created = True
        End If
        Return created
    End Function

    Private Function CreateDatabaseServer() As Boolean
        Dim created As Boolean = False
        Dim errorMessage As String = String.Empty
        If Not DataScript.IsValidServer(txtServer.Text, errorMessage) Then
            Dim message As String = String.Format("Unable to connect to server {0}.", txtServer.Text)
            message += Environment.NewLine + "Please check the name of the server and that you have permissions to c"
            MessageBox.Show(Me, "Unable to connect to the server A new database has been created successfully. Please configure the system settings for this database.", "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Function
        End If

        If Not DataScript.IsExistingDatabase(txtServer.Text, txtDatabase.Text, errorMessage) Then
            DataScript.CreateEmptyDatabase(txtServer.Text, txtDatabase.Text, errorMessage)
        End If

        DataScript.CreateDatabase(txtServer.Text, txtDatabase.Text)
        
        _configurationHelper.SaveConnectionStringServer(txtServer.Text, txtDatabase.Text) 'Connect to this new database

        MessageBox.Show(Me, "A new database has been created successfully. Please configure the system settings for this database.", "Database Created", MessageBoxButtons.OK, MessageBoxIcon.Information)
        created = True

        Return created
    End Function

    Public Shared Sub CopyDatabase(ByVal filePath As String)
        Dim folder = Path.GetDirectoryName(filePath)
        If Not Directory.Exists(folder) Then
            Directory.CreateDirectory(folder)
        End If
        Dim sourceFolder = Path.Combine(Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly().Location), "Database")
        File.Copy(Path.Combine(sourceFolder, "BlankDatabase.mdf"), filePath)
    End Sub


    Private Sub cboServerOrFile_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboServerOrFile.SelectedIndexChanged
        pnlServer.Enabled = (ConnectionType = TYPE_SQL_SERVER)
        pnlDatabaseFile.Enabled = Not pnlServer.Enabled

    End Sub

    Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
        Dim result As Boolean
        If IsCreateDatabase Then
            result = CreateDatabase()
        Else
            result = OpenDatabase()
        End If
        If result Then
            DialogResult = Windows.Forms.DialogResult.OK
            Me.Close()
        End If
    End Sub

    Private ReadOnly Property ConnectionType() As Integer
        Get
            Return cboServerOrFile.SelectedIndex
        End Get
    End Property

    Private Sub SaveConnectionString()
        If ConnectionType = TYPE_FILE Then
            _configurationHelper.SaveConnectionStringFile(txtDatabasePath.Text)
        Else
            _configurationHelper.SaveConnectionStringServer(txtServer.Text, txtDatabase.Text)
        End If
    End Sub
End Class